package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.result.Result;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.VO.UserBindVO;
import com.atguigu.srb.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author ZLHao
 * @since 2021-07-12
 */
@Api(tags = "会员账号绑定")
@Slf4j
@RestController
@RequestMapping("/api/core/userBind")
public class UserBindController {

    @Autowired
    private UserBindService userBindService;

    /**
     * @description: 绑定用户提交的数据
     * @param: userBindVO
     * @param: request
     * @return: com.atguigu.common.result.Result
     * @author Administrator
     * @date: 2021/7/20 0020 10:26
     */
    @ApiOperation("账户绑定提交数据")
    @PostMapping("/auth/bind")
    public Result bind(@RequestBody UserBindVO userBindVO , HttpServletRequest request){

        // 先从请求头中拿到 token
        String token = request.getHeader("token");
        // 检验token,未登录时抛出异常，登录成功时，拿到登录用户的id
        Long userId = JwtUtils.getUserId(token);
        // 将用户输入的数据提交，生成post表单
       String forms =  userBindService.bind(userBindVO,userId);
        return  Result.ok().data("formStr",forms);

    }

    @PostMapping("/notify")
    public String  notify(HttpServletRequest request){
        // 得到请求体的内容
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 利用工具类解析出来String,object格式
        Map<String, Object> paramMap = RequestHelper.switchMap(parameterMap);
        log.info("用户账号绑定异步回调：" + JSON.toJSONString(paramMap));


        // 校验签名
        // 返回的是加密后的sign
        if (!RequestHelper.isSignEquals(paramMap)){
            log.error("用户账号绑定异步回调签名错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }

        // 需要写入数据库
        userBindService.notifyMethod(paramMap);

        return "success";
    }


}

